<template>
  <el-card style="width: 1000px; margin: 0 auto;">

    <el-tabs v-model="businessType" @tabChange="handleQuery">
      <el-tab-pane label="菜品" :name="1"></el-tab-pane>
      <el-tab-pane label="旧物" :name="2"></el-tab-pane>
    </el-tabs>

    <div v-if="cartList.length">
      <el-table
          ref="table"
          :cell-style="() => ({ textAlign: 'center' })"
          :data="cartList"
          :header-cell-style="() => ({ textAlign: 'center' })"
          :row-style="() => ({ height: 'center' })"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="商品图片" width="130">
          <template v-slot="scope">
            <base-image :src="scope.row.image"/>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="240">
          <template v-slot="scope">
            <p class="center">{{ scope.row.name }}</p>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="150">
          <template v-slot="scope">
            <el-input-number
                v-model="scope.row.count"
                :max="100"
                :min="1"
                class="center"
                label="描述文字"
                size="small"
                step-strictly
                @change="handleChange(scope.row.id, scope.row.count)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100" prop="stock"></el-table-column>
        <el-table-column label="单价" width="100">
          <template v-slot="scope">
            <p class="price">￥{{ scope.row.price }}</p>
          </template>
        </el-table-column>
        <el-table-column label="总价" width="100">
          <template v-slot="scope">
            <p class="price">￥{{ (scope.row.price * scope.row.count).toFixed(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template v-slot="scope">
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.id)"
            >
              <el-icon>
                <Delete/>
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 20px">
        <el-col :offset="2" :span="7">
          <span>购买总数量:</span>
          <el-badge :value="totalNum" color="orange"></el-badge>
        </el-col>

        <el-col :span="7" class="flex-row">
          <span>购买总价:</span>
          <span class="price" style="font-size: 24px">￥{{ totalPrice }}</span>
        </el-col>
        <el-col :span="7">
          <el-button style="width: 100px" @click="handleOpenFinishDialog">
            <el-icon>
              <CircleCheckFilled/>
            </el-icon>
            <span>结算</span>
          </el-button>
          <el-button size="default" type="danger" @click="handleClear">
            <el-icon>
              <Delete/>
            </el-icon>
            <span>清空购物车</span>
          </el-button>
        </el-col>
      </el-row>
    </div>

    <el-empty v-else description="购物车为空"></el-empty>

    <OrderCreateDialog ref="orderRef" @success="handleCreateOrderSuccess"></OrderCreateDialog>
  </el-card>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {ElMessage, ElNotification} from 'element-plus'
import {confirm} from "@/utils/utils.js"
import request from "@/utils/request.js"
import {CircleCheckFilled, Delete} from "@element-plus/icons-vue"
import BaseImage from "@/components/common/BaseImage.vue";
import OrderCreateDialog from "@/components/OrderCreateDialog.vue";

const cartList = ref([])
const businessType = ref(1)
// 生命周期钩子
onMounted(() => {
  handleQuery()
})

const handleSelectionChange = (rows) => {
  // 更新选中状态
  cartList.value.forEach(cart => {
    cart.isSelected = rows.some(row => row.id === cart.id)
  })
}

const handleQuery = async () => {
  cartList.value = await request.get('/cart/list', {
    params: {businessType: businessType.value}
  })
  cartList.value.forEach(e => {
    e.isSelected = false
  })
}

// 添加表格引用
const table = ref(null)

// 修改计算属性，使用表格的实际选中状态
const totalPrice = computed(() => {
  return cartList.value.reduce((sum, cart) => {
    return cart.isSelected ? sum + (cart.price * cart.count) : sum
  }, 0)
})

const totalNum = computed(() => {
  return cartList.value.reduce((sum, cart) => {
    return cart.isSelected ? sum + cart.count : sum
  }, 0)
})

const selectedCartList = computed(() => cartList.value.filter(e => e.isSelected))

const handleChange = async (id, count) => {
  await request.put('/cart', {id: id, count: count})
}

const handleDelete = async (id) => {
  await request.delete('/cart/' + id)
  await handleQuery()
  ElMessage.success('移除购物车成功')
}

const orderRef = ref(null)
const handleOpenFinishDialog = () => {
  if (selectedCartList.value.length === 0) {
    ElNotification.warning('请至少选择一个商品进行结算')
    return
  }
  orderRef.value.open(selectedCartList.value, businessType.value)
}

const handleCreateOrderSuccess = async () => {
  const ids = selectedCartList.value.map(e => e.id)
  await request.post('/cart/clear', ids)
  await handleQuery()
}

const handleClear = () => {
  confirm('是否清空购物车?', async () => {
    await request.post('/cart/clear')
    await handleQuery()
    ElMessage.success('清空购物车成功')
  })
}
</script>

<style scoped>
.el-col {
  line-height: 32px;
}

.el-badge {
  line-height: 20px;
}
</style>